package com.hn.it.qwen01.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.hn.it.qwen01.service.QianWenAiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/api")
public class QianWenAiController {

    @Autowired
    private QianWenAiService qianWenAiService;

    //经典的跨域问题，声明这个网站的可以访问，跨域请求
    @CrossOrigin(origins = "*")
    //    表示任意ip网址
//    @CrossOrigin(origins = "http://localhost:5173")
    @PostMapping("/generate")
    public Map<String, Object> generateMessage
            (@RequestParam String userPrompt, HttpSession session, @RequestParam int maxTokens , @RequestParam String role)
            throws NoApiKeyException, InputRequiredException
    {
        System.out.println("Received userPrompt: " + userPrompt);
        List<String> messages = (List<String>) session.getAttribute("history");
        if(messages==null){
            messages = new LinkedList<>();
            session.setAttribute("history",messages);
        }
        messages.add("用户说:"+userPrompt);
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<messages.size();i++){
            sb.append(messages.get(i));
            sb.append("\n");
        }
        Generation gen = new Generation();
        String prompt = qianWenAiService.generatePrompt(role);

        sb.append(prompt); // 添加角色情景到提示
        String finalPrompt = sb.toString();

        QwenParam params = QwenParam.builder().model("qwen-turbo")
                //.apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .prompt(finalPrompt)
                .seed(222)
                .topP(0.9)
                .resultFormat("messages")
                .enableSearch(false)
                .maxTokens(maxTokens)
                .temperature(0.9f)
                .repetitionPenalty(1.0f)
                .build();

        GenerationResult result = gen.call(params);
        System.out.println(result);

        String answer = result.getOutput().getChoices().get(0).getMessage().getContent();
        messages.add("AI:"+answer);

        if(messages.size()>6){
            messages.remove(0);
            messages.remove(0);
        }
        Map<String, Object> response = new HashMap<>();
        try {
            String generatedText = qianWenAiService.callWithMessage(userPrompt,session, maxTokens,role);
            response.put("output", Collections.singletonMap("text", generatedText));
        } catch (NoApiKeyException | ApiException | InputRequiredException e) {
            response.put("error", "Error: " + e.getMessage());
        }

        return response;
    }
}
